package com.skyworth.web.waiter;

import com.skyworth.utils.CookieUtil;
import com.skyworth.utils.StrUtil;
import com.skyworth.web.admin.user.domain.UserModel;
import com.skyworth.web.admin.user.service.UserService;
import com.skyworth.web.common.Constants;
import com.skyworth.web.common.controller.BaseController;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * Created by cody on 2016/8/11.
 *
 * 服务员端相关页面
 *
 *
 */
@Controller
@RequestMapping(value="/waiter")
public class WaiterController extends BaseController {

    @Autowired
    UserService userService;

    @RequestMapping(value = {"/wechat"},method = RequestMethod.GET)
    public String wechat(HttpServletResponse response){
        CookieUtil.setCookie("appkey","abcde",response);
        CookieUtil.setCookie("abcde_uid","cody",response);
        CookieUtil.setCookie("cookie_store_id","5",response);
        CookieUtil.setCookie("bindtabid","16",response);
        return "m/index";
    }

    @RequestMapping(value={"/index"},method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){

        //没有登录
        UserModel userModel = currentUser();

        boolean isLogin = false;
        try{
            if(userModel == null){
                //cookies 是否有记录，有的话登录，没有弹出登录
                String username = CookieUtil.getCookie(Constants.COOKIE_USER_KEY,request);
                username = URLDecoder.decode(username,"UTF-8");
                if(!StrUtil.isEmpty(username)){
                    String password = CookieUtil.getCookie(Constants.COOKIE_PASSWORD_KEY,request); //md5密码
                    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                    isLogin = isLogin(token);

                    if(isLogin){
                        userModel = userService.findUserByUsername(username);
                        WaiterCookie.writeSuccesCookie(username, userModel,response);
                    }
                }
            }else{
                isLogin = true;
            }
        }catch (Exception e){
            e.printStackTrace();
            isLogin = false;
        }

        if(!isLogin){
            WaiterCookie.writeErrorCookie(response);
        }


        return "m/waiter";
    }


}
